<template>
  <el-upload
      :before-upload="beforeAvatarUpload"
      :http-request="httprequest"
      :on-success="handleAvatarSuccess"
      :show-file-list="false"
      action="#"
      class="avatar-uploader"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
    <el-icon v-else class="avatar-uploader-icon">
      <Plus/>
    </el-icon>
  </el-upload>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue'
import type {UploadProps} from 'element-plus'
import {ElLoading, ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import axios from "axios";
import {useUserInfoStore} from '@/stores/User/UserInfo'
import router from "@/router";

const UserInfoStore = useUserInfoStore()
const imageUrl = ref('')
onMounted(function imageUrlRestart() {
  imageUrl.value = UserInfoStore.userAvatarUrl
})
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/png' && rawFile.type !== 'image/jpeg') {
    ElMessage.error('请选择png/jpg格式的图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('请选择小于1M的图片')
    return false
  }
  return true
}
const httprequest = (file) => {
  let formData = new FormData()
  const loading = ElLoading.service({
    lock: true,
    text: '正在上传头像',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  console.log(file.file)
  let temp = file.file
  if (temp) {
    formData.append('file', temp)
    imageUrl.value = window.URL.createObjectURL(temp)
    axios({
      headers: {
        "Content-Type": "multipart/form-data",
      },
      timeout: 60000,
      method: "POST",
      url: "/user/saveImg",
      data: formData,
      params: {
        userId: UserInfoStore.userId
      }
    }).then(res => {
      if (res != null) {
        sessionStorage.clear()
        loading.close()
        router.push('/login')
      } else {
        loading.close()
        alert("更新头像失败")
      }
    })
  }

}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
